package com.yiwei.zxp.activity;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Editable;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yiwei.zxp.R;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.bean.GoodsTypeMoreBean;
import com.yiwei.zxp.api.bean.ShopAuthAddBean;
import com.yiwei.zxp.base.BaseActivity;
import com.yiwei.zxp.constant.Const;
import com.yiwei.zxp.event.AreaAddressEvent;
import com.yiwei.zxp.event.SettingShopEvent;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.Spans;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.UI;
import com.yiwei.zxp.util.Util;
import com.yiwei.zxp.view.GoodsTypeMoreDilaog;
import com.yiwei.zxp.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class SettingShopActivity extends BaseActivity implements GoodsTypeMoreDilaog.OnChooseListener {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.txt_shop_name)
    TextView txtShopName;
    @BindView(R.id.edit_shop_name)
    EditText editShopName;
    @BindView(R.id.txt_address)
    TextView txtAddress;
    @BindView(R.id.edit_address)
    TextView editAddress;
    @BindView(R.id.txt_phone)
    TextView txtPhone;
    @BindView(R.id.edit_phone)
    EditText editPhone;
    @BindView(R.id.txt_type)
    TextView txtType;
    @BindView(R.id.edit_type)
    TextView editType;
    @BindView(R.id.txt_identity)
    TextView txtIdentity;
    @BindView(R.id.edit_identity)
    TextView editIdentity;
    @BindView(R.id.edit_first_photo)
    TextView editFirstPhoto;
    @BindView(R.id.edit_service_code)
    EditText editServiceCode;
    @BindView(R.id.edit_invite_code)
    EditText editInviteCode;
    @BindView(R.id.layout_more)
    LinearLayout layoutMore;
    @BindView(R.id.btn_more)
    LinearLayout btnMore;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.img_up_down)
    ImageView imgUpDown;
    @BindView(R.id.txt_more_or_less)
    TextView txtMoreOrLess;
    private ShopAuthAddBean submitBean;
    private Unbinder unbiner;
    private int x28;
    private GoodsTypeMoreDilaog goodsTypeDilaog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settting_shop);
        initWebViewBar();
        unbiner = ButterKnife.bind(this);
        init();
        EventBus.getDefault().register(this);
    }

    private void init() {
        submitBean = new ShopAuthAddBean();
        txtTitle.setText("设置店铺");
        x28 = getResources().getDimensionPixelSize(R.dimen.x28);
        setRedPoint(txtPhone, "店铺电话");
        setRedPoint(txtAddress, "店铺地址");
        setRedPoint(txtIdentity, "资质认证");
        setRedPoint(txtShopName, "店铺名称");
        setRedPoint(txtType, "经营分类");
        goodsTypeDilaog = new GoodsTypeMoreDilaog(this).setOnChooseListener(this);
    }

    private void setRedPoint(TextView view, String text) {
        Spanned point = Spans.with(this).font(text, x28, 0xff000000).style(Typeface.BOLD).
                font("*", x28, 0xffFF0030).style(Typeface.BOLD).
                build();
        view.setText(point);
    }

    @OnTextChanged({R.id.edit_shop_name, R.id.edit_phone})
    void afterTextChanged(Editable s) {
        checkEmpty();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(AreaAddressEvent event) {
        if (TextUtils.isEmpty(event.areaId)) {
            submitBean.districts_id = null;
        } else {
            submitBean.districts_id = event.areaId;
        }
        submitBean.province_id = event.provinceId;
        submitBean.city_id = event.cityId;


        editAddress.setText(event.result + event.addressDetail);
        checkEmpty();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(SettingShopEvent event) {
        switch (event.event_type) {
            case Const.SettingShopType.First_Shop:
                submitBean.shop_img = event.shop_img;
                editFirstPhoto.setText("已上传");
                break;
            case Const.SettingShopType.Qualification:
                submitBean.type = event.type;
                if (event.type.equals("1")) {
                    submitBean.licence_name = event.licence_name;
                    submitBean.idcard_front_img = event.idcard_front_img;
                    submitBean.idcard_no = event.idcard_no;
                    submitBean.licence_img = event.licence_img;
                    submitBean.licence_no = event.licence_no;
                    submitBean.realname = event.realname;
                } else {
                    submitBean.idcard_front_img = event.idcard_front_img;
                    submitBean.idcard_no = event.idcard_no;
                    submitBean.realname = event.realname;
                    submitBean.idcard_back_img = event.idcard_back_img;
                    submitBean.idcard_hand_img = event.idcard_hand_img;
                }
                editIdentity.setText("已上传");
                checkEmpty();
                break;
        }
    }

    private void checkEmpty() {
        if (!TextUtils.isEmpty(UI.toString(editShopName)) &&
                !TextUtils.isEmpty(UI.toString(editAddress)) &&
                !TextUtils.isEmpty(UI.toString(editPhone)) &&
                !TextUtils.isEmpty(UI.toString(editType)) &&
                !TextUtils.isEmpty(UI.toString(editIdentity))) {
            btnSubmit.setSelected(true);
        } else {
            btnSubmit.setSelected(false);
        }

    }


    public void getShopAuthAdd(ShopAuthAddBean item) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        Api.api_service.getShopAuthAdd(item).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    Util.startActivity(this, ShopSubmitSuccessActivity.class);
                    finish();
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbiner.unbind();
        unbiner = null;
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.btn_submit, R.id.edit_address, R.id.btn_back, R.id.edit_type, R.id.edit_identity, R.id.edit_first_photo, R.id.btn_more})
    public void onViewClicked(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.edit_address:
                Util.startActivity(this, New_LocalActivity.class);
                break;
            case R.id.btn_submit:
                if (TextUtils.isEmpty(UI.toString(editShopName))) {
                    ToastUtil.makeText(this, "店铺名称不能为空");
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(editAddress))) {
                    ToastUtil.makeText(this, "店铺地址不能为空");
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(editPhone))) {
                    ToastUtil.makeText(this, "店铺电话不能为空");
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(editType))) {
                    ToastUtil.makeText(this, "经营分类不能为空");
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(editIdentity))) {
                    ToastUtil.makeText(this, "资质认证不能为空");
                    return;
                }
                submitBean.name = UI.toString(editShopName);
                submitBean.address = UI.toString(editAddress);
                submitBean.phone = UI.toString(editPhone);
                if (!TextUtils.isEmpty(UI.toString(editServiceCode))) {
                    submitBean.service_code = UI.toString(editServiceCode);
                }
                getShopAuthAdd(submitBean);
                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.edit_type:
                goodsTypeDilaog.show();
                break;
            case R.id.edit_identity:
                Intent intentIdentity = new Intent(this, QualificationIdentityActivity.class);
                if (!TextUtils.isEmpty(submitBean.type)) {
                    //验证类型（1：营业执照认证，2：无营业执照认证）
                    intentIdentity.putExtra("type", submitBean.type);
                    if (submitBean.type.equals("1")) {
                        intentIdentity.putExtra(Const.SettingShopData.License.licence_name, submitBean.licence_name);
                        intentIdentity.putExtra(Const.SettingShopData.License.idcard_front_img, submitBean.idcard_front_img);
                        intentIdentity.putExtra(Const.SettingShopData.License.idcard_no, submitBean.idcard_no);
                        intentIdentity.putExtra(Const.SettingShopData.License.licence_img, submitBean.licence_img);
                        intentIdentity.putExtra(Const.SettingShopData.License.licence_no, submitBean.licence_no);
                        intentIdentity.putExtra(Const.SettingShopData.License.realname, submitBean.realname);
                    } else if (submitBean.type.equals("2")) {
                        intentIdentity.putExtra(Const.SettingShopData.Idcard.idcard_front_img, submitBean.idcard_front_img);
                        intentIdentity.putExtra(Const.SettingShopData.Idcard.idcard_no, submitBean.idcard_no);
                        intentIdentity.putExtra(Const.SettingShopData.Idcard.realname, submitBean.realname);
                        intentIdentity.putExtra(Const.SettingShopData.Idcard.idcard_back_img, submitBean.idcard_back_img);
                        intentIdentity.putExtra(Const.SettingShopData.Idcard.idcard_hand_img, submitBean.idcard_hand_img);
                    }
                }
                startActivity(intentIdentity);
                overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
            case R.id.edit_first_photo:
                Intent intentFirst = new Intent(this, ShopFirstPhotoActivity.class);
                if (!TextUtils.isEmpty(submitBean.shop_img)) {
                    intentFirst.putExtra("url", submitBean.shop_img);
                }
                startActivity(intentFirst);
                overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
            case R.id.btn_more:
                if (layoutMore.getVisibility() == View.VISIBLE) {
                    layoutMore.setVisibility(View.GONE);
                    txtMoreOrLess.setText("展开更多可选");
                    imgUpDown.setImageResource(R.mipmap.img_icon_down);
                } else {
                    layoutMore.setVisibility(View.VISIBLE);
                    txtMoreOrLess.setText("收起更多可选");
                    imgUpDown.setImageResource(R.mipmap.img_icon_up);
                }
                break;
        }
    }

    @Override
    public void onChooseType(List<GoodsTypeMoreBean> item) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < item.size(); i++) {
            builder.append(item.get(i).name);
            builder.append(",");
        }
        builder.deleteCharAt(builder.length() - 1);
        editType.setText(builder.toString());

        StringBuilder builderId = new StringBuilder();
        for (int i = 0; i < item.size(); i++) {
            builderId.append(item.get(i).id);
            builderId.append(",");
        }
        builderId.deleteCharAt(builderId.length() - 1);
        submitBean.cate_id = builderId.toString();
//        actHelper.setCateId(id);
        checkEmpty();
    }
}
